package com.kili.recommend.data.task;

import com.kili.recommend.data.config.CustomConfig;
import com.kili.recommend.data.config.IConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

/**
 * 清理缓存
 *
 * @author fenny
 * @since 2019/08/29
 */
@Slf4j
@Component
public class ClearCacheTask {

    @Resource
    private CacheManager cacheManager;

    @Resource
    private CustomConfig customConfig;

    private static boolean FLAG = true;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 定时触发清理
     */
    @Scheduled(fixedRate = 10000)
    public void clearCache() {
        if (FLAG) {
            FLAG = false;
            try {
                Cache cache = cacheManager.getCache(IConstant.CACHE_TRACK_ID);
                if (cache != null && cache.getNativeCache() instanceof ConcurrentMap) {
                    ConcurrentMap<String, Long> concurrentMap = (ConcurrentMap) cache.getNativeCache();
                    for (Map.Entry<String, Long> entry : concurrentMap.entrySet()) {
                        String key = entry.getKey();
                        if (System.currentTimeMillis() - entry.getValue() > customConfig.getClearCacheInterval()) {
                            concurrentMap.remove(key);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("", e);
            } finally {
                FLAG = true;
            }
        }
    }
}
